from lib.config.index import sensor_config
from lib.sensors.ssd1306.oled import OLED
from lib.sensors.soil import LM393
import json
import asyncio

__service__ = "soil_oled"
__description__ = "oled show soil humidity"

soil = None
_oled = None

def init():
    global soil,_oled
    LM393config = sensor_config.get_sensor("LM393")
    A0 = LM393config["A0"]
    D0 = LM393config["D0"]

    oled_config = sensor_config.get_sensor("ssd1306")
    scl = oled_config["scl"]
    sda = oled_config["sda"]
    soil = LM393.Soil(A0, D0)

    f = open("/lib/sensors/oled/fonts/soil.json", "r")
    data = f.read()
    fonts = json.loads(data)
    f.close()

    _oled = OLED(scl, sda)
    _oled.font_renderer.set_font(fonts, 12)
    _oled.font_renderer.reset_line()
    _oled.font_renderer.show_text("开始测量数据...")


async def run():
    from lib.api import iot
    global soil, _oled

    while True:
        await asyncio.sleep(8)
        if not soil:
            continue
        v = soil.read_analog()
        hu = round(100 - v / 40.96, 2)
        value = {"humidity": hu, "value": v}
        data = f"{hu}, {v}"
        iot.upload_data(data, "Tiot_xtbrkh2t", value)

        if _oled:
            _oled.clear()
            _oled.font_renderer.auto_text(f"湿度: {hu}%", 0, 0, 12)
        
